import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export const useDataIntegrationStore = defineStore('dataIntegration', () => {
  // 状态
  const dataSources = ref([
    {
      id: 1,
      name: 'MES系统',
      type: 'mes',
      status: 'normal',
      lastSync: '2分钟前',
      icon: 'DataLine'
    },
    {
      id: 2,
      name: '工位数据',
      type: 'station',
      status: 'normal',
      lastSync: '1分钟前',
      icon: 'Monitor'
    },
    {
      id: 3,
      name: '设备运行数据',
      type: 'equipment',
      status: 'warning',
      lastSync: '5分钟前',
      icon: 'Setting'
    }
  ])

  const storageStatus = ref({
    usage: 65,
    realtimeData: 2.5,
    historicalData: 15.8
  })

  const backupStatus = ref({
    autoBackup: true,
    lastBackup: '2024-03-15 00:00',
    schedule: '每日 00:00'
  })

  const securityStatus = ref({
    encryption: true,
    accessControl: true,
    lastLogCheck: '2024-03-15 10:00'
  })

  // 计算属性
  const normalDataSources = computed(() => 
    dataSources.value.filter(source => source.status === 'normal')
  )

  const warningDataSources = computed(() => 
    dataSources.value.filter(source => source.status === 'warning')
  )

  // 方法
  const fetchDataSources = async () => {
    try {
      const response = await axios.get('/api/data-sources')
      dataSources.value = response.data
    } catch (error) {
      console.error('Failed to fetch data sources:', error)
    }
  }

  const fetchStorageStatus = async () => {
    try {
      const response = await axios.get('/api/storage-status')
      storageStatus.value = response.data
    } catch (error) {
      console.error('Failed to fetch storage status:', error)
    }
  }

  const fetchBackupStatus = async () => {
    try {
      const response = await axios.get('/api/backup-status')
      backupStatus.value = response.data
    } catch (error) {
      console.error('Failed to fetch backup status:', error)
    }
  }

  const fetchSecurityStatus = async () => {
    try {
      const response = await axios.get('/api/security-status')
      securityStatus.value = response.data
    } catch (error) {
      console.error('Failed to fetch security status:', error)
    }
  }

  const toggleAutoBackup = async (enabled) => {
    try {
      await axios.post('/api/backup-settings', { autoBackup: enabled })
      backupStatus.value.autoBackup = enabled
    } catch (error) {
      console.error('Failed to update backup settings:', error)
    }
  }

  return {
    // 状态
    dataSources,
    storageStatus,
    backupStatus,
    securityStatus,
    // 计算属性
    normalDataSources,
    warningDataSources,
    // 方法
    fetchDataSources,
    fetchStorageStatus,
    fetchBackupStatus,
    fetchSecurityStatus,
    toggleAutoBackup
  }
}) 